"""
Illustrious CSV-to-Dict Converter
---------------------------------

This utility converts WebUI-style CSV lists (artists/characters) into
Python dictionaries for use in the Illustrious custom node.

Usage:
  python illustrious-list-convert.py input.csv output.py var_name

Example:
  python illustrious-list-convert.py danbooru_artist_webui.csv artists_small.py ARTISTS

Notes:
- Input CSV should have two columns: key,value (header optional)
- Output is a Python module that defines the provided variable
"""

import csv
import sys


def convert_csv_to_py(input_path: str, output_path: str, var_name: str) -> None:
    mapping: dict[str, str] = {}
    with open(input_path, newline="", encoding="utf-8") as f:
        reader = csv.reader(f)
        rows = list(reader)

    # If header present, detect and skip
    if rows and any(cell.lower() in {"key", "name"} for cell in rows[0]):
        rows = rows[1:]

    for row in rows:
        if not row or len(row) < 2:
            continue
        key = row[0].strip()
        val = row[1].strip()
        if key and val:
            mapping[key] = val

    with open(output_path, "w", encoding="utf-8") as out:
        out.write("# Auto-generated by illustrious-list-convert.py\n")
        out.write(f"{var_name} = {mapping!r}\n")


def main(argv: list[str]) -> int:
    if len(argv) != 4:
        print("Usage: python illustrious-list-convert.py input.csv output.py VAR_NAME")
        return 2
    _, inp, outp, var = argv
    convert_csv_to_py(inp, outp, var)
    print(f"Wrote {outp} with variable {var} ({inp} -> {outp})")
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))
